package com.aofeng.hybrid.service;

import android.content.Context;
import android.os.StrictMode;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 调用rest服务
 * Created by LGY on 2016-07-04.
 */
public class RestService extends GenericService{

    public RestService(Context context) {
        super(context);
    }

    @Override
    public JSONObject action(JSONObject json){
        JSONObject result = new JSONObject();
        try {
            result.put("code", 500);
            result.put("data", "不可处理异常。");
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Object obj = execute(json);
            String s = String.valueOf(obj);
            result.put("code", 200);
            result.put("data", s);
            return result;
        } catch(Exception e) {
            try {
                result.put("code", 500);
                result.put("data", e.getMessage());
                return result;
            } catch (Exception ex) {
                //suck
                return result;
            }
        }
    }

    /**
     * 执行rest服务
     * @param json 格式 {action:[post|get], url:url, data:data}
     * @return
     * @throws Exception
     */
    public Object execute(JSONObject json) throws Exception{
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        String method = json.getString("action");
        String result;
        if(method.toLowerCase().equals("get")) {
            HttpGet getMethod = new HttpGet(json.getString("url"));
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(getMethod);
            result = EntityUtils.toString(response.getEntity(), "UTF8");
        }else if(method.toLowerCase().equals("post")) {
            HttpPost httpPost = new HttpPost(json.getString("url"));
            httpPost.setEntity(new StringEntity(json.getString("data"), "UTF8"));
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(httpPost);
            result =  EntityUtils.toString(response.getEntity(), "UTF8");
        }else {
            throw  new Exception("不支持的rest调用方式。");
        }
        JSONArray array;
        if(result.startsWith("{"))
            array =  new JSONArray("[" + result + "]");
        else if(result.startsWith("["))
            array = new JSONArray(result);
        else
            throw  new Exception("调用rest服务失败。");
        parseArray(array, list);
        return list;
    }

    /**
     * 解析JSON数组
     * @param array 数组
     * @param list   解析后的map列表
     * @return
     */
    private boolean parseArray(JSONArray array, List<Map<String, Object>> list) {
        try
        {
            for(int i=0; i<array.length(); i++)
            {
                JSONObject obj = array.getJSONObject(i);
                Map<String, Object> map = new HashMap<String, Object>();
                list.add(map);
                if(!parseJSON(obj, map))
                    return false;
            }
            return true;
        }
        catch(Exception e)
        {
            return false;
        }
    }

    /**
     * 解析json对象
     * @param obj 对象
     * @param map 对象键值字典
     * @return
     */
    private boolean parseJSON(JSONObject obj, Map<String, Object> map) {
        try
        {
            @SuppressWarnings("unchecked")
            Iterator<String> itr = obj.keys();
            while(itr.hasNext())
            {
                String key = itr.next();
                Object property = obj.get(key);
                ValueWrapper wrapper = new ValueWrapper();
                if(!parseProperty(property, wrapper))
                    return false;
                map.put(key, wrapper.value);
            }
            return true;
        }
        catch(Exception e)
        {
            return false;
        }
    }

    /**
     * 解析属性
     * @param property 属性
     * @param wrapper 属性值
     * @return
     */
    private boolean parseProperty(Object property, ValueWrapper wrapper) {
        if(property instanceof JSONArray)
        {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            if(!parseArray((JSONArray)property, list))
                return false;
            wrapper.value=list;
        }
        else if(property instanceof JSONObject)
        {
            Map<String, Object> map = new HashMap<String, Object>();
            if(!parseJSON((JSONObject)property,map))
                return false;
            wrapper.value = map;
        }
        else
            wrapper.value = property;
        return true;
    }

}

/**
 * 封装属性值，传参数用
 * @author Administrator
 *
 */
class ValueWrapper
{
    public Object value;
}

